package com.jason.campusinn.utils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import com.jason.campusinn.CampusInnApp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;


public class HttpUtil {
	/**
	 * 打印接口的Log
	 */
	private static String HTTP_UTIL_LOG = "httputil";
	/**
	 * 文件已下载完成
	 */
	public static final String FILE_DOWNLOAD_COMPLETE = "maybe the file has downloaded completely";
	/**
	 * 文件已下载所返回异常code
	 */
	public static final int FILE_DOWNLOAD_EXCEPTION_CODE = 416;

	/**
	 * --------------------------------------xutils框架--------------------------
	 * -------------------------------------------
	 */
	/**
	 * 文件下载
	 * 
	 * @param url
	 *            文件下载地址
	 * @param fileName
	 *            文件本地存储完整路径如：xzhiliao-2.4.0.apk
	 * @param callBack
	 *            进度回调接口
	 * @return handler对象，方便取消下载，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler downloadFile(String url, String fileName,
			RequestCallBack<File> callBack) {
		HttpHandler handler = new HttpUtils().download(url, fileName, callBack);
		return handler;
	}

	/**
	 * 文件下载
	 * 
	 * @param url
	 *            文件下载地址
	 * @param fileName
	 *            文件本地存储完整路径如：xzhiliao-2.4.0.apk
	 * @param isContinue
	 *            是否断点下载
	 * @param callBack
	 *            进度回调接口
	 * @return handler对象，方便取消下载，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler downloadFile(String url, String fileName,
			boolean isContinue, RequestCallBack<File> callBack) {
		HttpHandler handler = new HttpUtils().download(url, fileName,
				isContinue, callBack);
		return handler;
	}

	/**
	 * 文件下载
	 * 
	 * @param url
	 *            文件下载地址
	 * @param fileName
	 *            文件本地存储完整路径如：xzhiliao-2.4.0.apk
	 * @param isContinue
	 *            是否断点下载
	 * @param isReName
	 *            下载完成后文件是否重命名为下载文件的名称
	 * @param callBack
	 *            进度回调接口
	 * @return handler对象，方便取消下载，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler downloadFile(String url, String fileName,
			boolean isContinue, boolean isReName, RequestCallBack<File> callBack) {
		HttpHandler handler = new HttpUtils().download(url, fileName,
				isContinue, isReName, callBack);
		return handler;
	}

	/**
	 * 文件下载
	 * 
	 * @param url
	 *            文件下载地址
	 * @param fileName
	 *            文件本地存储完整路径如：xzhiliao-2.4.0.apk
	 * @param params
	 *            提交的参数信息
	 * @param callBack
	 *            进度回调接口
	 * @return handler对象，方便取消下载，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler downloadFile(String url, String fileName,
			RequestParams params, RequestCallBack<File> callBack) {
		HttpHandler handler = new HttpUtils().download(url, fileName, params,
				callBack);
		params = new RequestParams();
		return handler;
	}

	/**
	 * 文件下载
	 * 
	 * @param url
	 *            文件下载地址
	 * @param fileName
	 *            文件本地存储完整路径如：xzhiliao-2.4.0.apk
	 * @param params
	 *            提交的参数信息
	 * @param isContinue
	 *            是否断点下载
	 * @param callBack
	 *            进度回调接口
	 * @return handler对象，方便取消下载，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler downloadFile(String url, String fileName,
			RequestParams params, boolean isContinue,
			RequestCallBack<File> callBack) {
		HttpHandler handler = new HttpUtils().download(url, fileName, params,
				isContinue, callBack);
		params = new RequestParams();
		return handler;
	}

	/**
	 * 文件下载
	 * 
	 * @param method
	 *            下载方式:HttpMethod.POST;HttpMethod.GET
	 * @param url
	 *            文件下载地址
	 * @param fileName
	 *            文件本地存储完整路径如：xzhiliao-2.4.0.apk
	 * @param params
	 *            提交的参数信息
	 * @param callBack
	 *            进度回调接口
	 * @return handler对象，方便取消下载，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler downloadFile(HttpMethod method, String url,
			String fileName, RequestParams params,
			RequestCallBack<File> callBack) {
		HttpHandler handler = new HttpUtils().download(method, url, fileName,
				params, callBack);
		return handler;
	}

	/**
	 * 文件下载
	 * 
	 * @param method
	 *            下载方式:HttpMethod.POST;HttpMethod.GET
	 * @param url
	 *            文件下载地址
	 * @param fileName
	 *            文件本地存储完整路径如：xzhiliao-2.4.0.apk
	 * @param params
	 *            提交的参数信息
	 * @param isContinue
	 *            是否支持断点下载
	 * @param callBack
	 *            进度回调接口
	 * @return handler对象，方便取消下载，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler downloadFile(HttpMethod method, String url,
			String fileName, RequestParams params, boolean isContinue,
			RequestCallBack<File> callBack) {
		HttpHandler handler = new HttpUtils().download(method, url, fileName,
				params, isContinue, callBack);
		return handler;
	}

	/**
	 * 文件下载
	 * 
	 * @param url
	 *            文件下载地址
	 * @param fileName
	 *            文件本地存储完整路径如：xzhiliao-2.4.0.apk
	 * @param params
	 *            提交的参数信息
	 * @param isContinue
	 *            是否支持断点下载
	 * @param isContinue
	 *            下载完成后，文件是否重命名
	 * @param callBack
	 *            进度回调接口
	 * @return handler对象，方便取消下载，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler downloadFile(String url, String fileName,
			RequestParams params, boolean isContinue, Boolean isReName,
			RequestCallBack<File> callBack) {
		HttpHandler handler = new HttpUtils().download(url, fileName, params,
				isContinue, isReName, callBack);
		return handler;
	}

	/**
	 * 文件下载
	 * 
	 * @param method
	 *            下载方式:HttpMethod.POST;HttpMethod.GET
	 * @param url
	 *            文件下载地址
	 * @param fileName
	 *            文件本地存储完整路径如：xzhiliao-2.4.0.apk
	 * @param params
	 *            提交的参数信息
	 * @param isContinue
	 *            是否支持断点下载
	 * @param isContinue
	 *            下载完成后，文件是否重命名
	 * @param callBack
	 *            进度回调接口
	 * @return handler对象，方便取消下载，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler downloadFile(HttpMethod method, String url,
			String fileName, RequestParams params, boolean isContinue,
			Boolean isReName, RequestCallBack<File> callBack) {
		HttpHandler handler = new HttpUtils().download(method, url, fileName,
				params, isContinue, isReName, callBack);
		return handler;
	}

	/**
	 * 文件下载
	 * 
	 * @param method
	 *            下载方式:HttpMethod.POST;HttpMethod.GET
	 * @param url
	 *            文件下载地址
	 * @param fileName
	 *            文件本地存储完整路径如：xzhiliao-2.4.0.apk
	 * @param params
	 *            提交的参数信息
	 * @param isContinue
	 *            是否支持断点下载
	 * @param isContinue
	 *            下载完成后，文件是否重命名
	 * @param outTime
	 *            超时时间
	 * @param callBack
	 *            进度回调接口
	 * @return handler对象，方便取消下载，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler downloadFile(HttpMethod method, String url,
			String fileName, RequestParams params, boolean isContinue,
			Boolean isReName, long outTime, RequestCallBack<File> callBack) {
		HttpUtils http = new HttpUtils();
		http.configCurrentHttpCacheExpiry(outTime);
		HttpHandler handler = new HttpUtils().download(method, url, fileName,
				params, isContinue, isReName, callBack);
		return handler;
	}

	/**
	 * 文件上传
	 * 
	 * @param method
	 *            上传方式:HttpMethod.POST;HttpMethod.GET
	 * @param url
	 *            上传地址
	 * @param callback
	 *            回调进度，
	 * @return 对象，方便取消上传，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler upLoadFile(HttpMethod method, String url,
			RequestCallBack<File> callback) {
		HttpHandler handler = new HttpUtils().send(method, url, callback);
		return handler;
	}

	/**
	 * 文件上传
	 * 
	 * @param method
	 *            上传方式:HttpMethod.POST;HttpMethod.GET
	 * @param url
	 *            上传地址
	 * @param params
	 *            参数信息
	 * @param callback
	 *            回调进度，返回值 onSuccess(ResponseInfo<File> arg0);String result =
	 *            arg0.result + ""
	 * @return 对象，方便取消上传，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler upLoadFile(HttpMethod method, String url,
			RequestParams params, RequestCallBack<File> callback) {
		HttpHandler handler = new HttpUtils().send(method, url, params,
				callback);
		return handler;
	}

	/**
	 * 文件上传
	 * 
	 * @param method
	 *            上传方式:HttpMethod.POST;HttpMethod.GET
	 * @param url
	 *            上传地址
	 * @param params
	 *            参数信息
	 * @param callback
	 *            回调进度，
	 * @param outTime
	 *            超时时间
	 * @return 对象，方便取消上传，控制是否继续
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler upLoadFile(HttpMethod method, String url,
			RequestParams params, HttpRequestCallBack<File> callback,
			long outTime) {
		HttpUtils http = new HttpUtils();
		http.configCurrentHttpCacheExpiry(outTime);
		HttpHandler handler = http.send(method, url, params, callback);
		return handler;
	}

	/*
	*//**
	 * Http请求
	 * 
	 * @param method
	 * @param url
	 * @param callBack
	 * @param <T>
	 *            返回值类型
	 * @return
	 */
	/*
	 * @SuppressWarnings("rawtypes") public static <T> HttpHandler
	 * sendRequest(HttpMethod method,String url,HttpRequestCallBack<T>
	 * callBack){ return sendRequest(method, url, null, callBack); }
	 * 
	 * public static <T> HttpHandler sendRequest(HttpMethod method,String
	 * url,HttpRequestCallBack<T> callBack, long timeOut){ HttpUtils http = new
	 * HttpUtils(); http.configSoTimeout((int)timeOut); return http.send(method,
	 * url, null, callBack); }
	 *//**
	 * Http请求
	 * 
	 * @param method
	 * @param url
	 * @param map
	 *            参数
	 * @param callBack
	 * @param <T>
	 *            返回值类型
	 * @return
	 */
	/*
	 * @SuppressWarnings("rawtypes") public static <T> HttpHandler
	 * sendRequest(HttpMethod method,String url,Map<String,String>
	 * map,HttpRequestCallBack<T> callBack){ List<NameValuePair> param = new
	 * ArrayList<NameValuePair>(); // 参数 StringBuffer result= new
	 * StringBuffer(); if (map != null) { Iterator<Entry<String, String>>
	 * iterator = map.entrySet().iterator(); while (iterator.hasNext()) {
	 * Entry<String, String> entry = iterator.next(); param.add(new
	 * BasicNameValuePair(entry.getKey(), entry.getValue()));
	 * result.append("&").
	 * append(entry.getKey()).append("=").append(entry.getValue()); } }
	 * if(result.length() > 0){ LogUtil.i(url + "?" +
	 * result.deleteCharAt(0).toString()); }else{ LogUtil.i(url); }
	 * RequestParams params = new RequestParams();
	 * params.addBodyParameter(param); return sendRequest(method, url, params,
	 * callBack, 60000); }
	 *//**
	 * Http请求
	 * 
	 * @param method
	 * @param url
	 * @param params
	 *            参数
	 * @param callBack
	 * @param timeOut
	 *            超时时间
	 * @param <T>
	 *            返回值类型
	 * @return
	 */
	/*
	 * @SuppressWarnings("rawtypes") public static <T> HttpHandler
	 * sendRequest(HttpMethod method,String url,RequestParams
	 * params,HttpRequestCallBack<T> callBack,long timeOut){ HttpUtils http =
	 * new HttpUtils(); http.configSoTimeout((int)timeOut); HttpHandler handler
	 * = http.send(method, url, params, callBack); return handler; }
	 */

	/**
	 * Http请求
	 * 
	 * @param method
	 * @param url
	 * @param map
	 *            参数
	 * @param callBack
	 * @param timeOut
	 *            超时时间(ms)
	 * @param <T>
	 *            返回值类型
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static <T> HttpHandler sendRequest(HttpMethod method, String url,
			Map<String, String> map, HttpRequestCallBack<T> callBack,
			long timeOut) {
		Log.d("000", "url: " + url);
		List<NameValuePair> param = new ArrayList<NameValuePair>(); // 参数
		StringBuffer result = new StringBuffer();
		if (map != null) {
			Iterator<Entry<String, String>> iterator = map.entrySet()
					.iterator();
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				param.add(new BasicNameValuePair(entry.getKey(), entry
						.getValue()));
				result.append("&").append(entry.getKey()).append("=")
						.append(entry.getValue());
			}
		}
		if (result.length() > 0) {
			LogUtil.i(url + "?" + result.deleteCharAt(0).toString());
		} else {
			LogUtil.i(url);
		}
		RequestParams params = new RequestParams();
		params.setHeader("X-AUTH-TOKEN", "add token here");
		params.addBodyParameter(param);
		HttpUtils http = new HttpUtils();
		if (timeOut > 0) {
			http.configSoTimeout((int) timeOut);
		}
		params.setContentType("application/json");
		return http.send(method, url, params, callBack);

	}

	/**
	 * Http请求
	 * 
	 * @param method
	 * @param url
	 *            参数
	 * @param callBack
	 * @param timeOut
	 *            超时时间(ms)
	 * @param <T>
	 *            返回值类型
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static <T> HttpHandler sendJsonRequest(HttpMethod method,
			String url, String json, HttpRequestCallBack<T> callBack,
			long timeOut) {
		LogUtil.d("接口 URL = " + url);
		LogUtil.d("接口 json = " + json);
		HttpUtils http = new HttpUtils();
		if (timeOut > 0) {
			http.configTimeout((int) timeOut);
		}
		RequestParams params = new RequestParams();

		try {
			if (json != null) {
				params.setBodyEntity(new StringEntity(json, "UTF-8"));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		params.setContentType("application/json");
		// 设置默认请求的缓存时间
		http.configDefaultHttpCacheExpiry(5);
		http.configHttpCacheSize(0);
		http.configRequestRetryCount(0);
		params.setHeader("X-AUTH-TOKEN", "add token here");
		LogUtil.d("接口 X-AUTH-TOKEN " + "add token here");
		return http.send(method, url, params, callBack);

	}

	// /**
	// * 判断网络是否连接
	// *
	// * @param context
	// * @return
	// */
	// public static boolean isNetworkConnected(Context context) {
	// if (context != null) {
	// ConnectivityManager mConnectivityManager = (ConnectivityManager) context
	// .getSystemService(Context.CONNECTIVITY_SERVICE);
	// NetworkInfo mNetworkInfo = mConnectivityManager
	// .getActiveNetworkInfo();
	// if (mNetworkInfo != null) {
	// return mNetworkInfo.isAvailable();
	// }
	// }
	// return false;
	// }

	/**
	 * ----------------------------------自封装http请求------------------------------
	 * --------------------------------
	 */

	/**
	 * http访问数据，默认返回的数据为UTF-8编码
	 * 
	 * @param url
	 *            url地址
	 * @return
	 * @throws IOException
	 */
	public static String getUrl(String url) throws IOException {
		HttpGet request = new HttpGet(url);
		LogUtil.i(url);
		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = httpClient.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			return EntityUtils.toString(response.getEntity());
		} else {
			return "";
		}
	}

	/**
	 * post提交数据
	 * 
	 * @param url
	 *            提交地址
	 * @param params
	 *            参数
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String postUrl(String url, Map<String, String> params)
			throws ClientProtocolException, IOException, TimeoutException {
		return postUrl(url, params, "UTF-8", 60 * 1000);
	}

	/**
	 * post提交数据
	 * 
	 * @param url
	 *            提交地址
	 * @param params
	 *            参数
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String postUrl(String url, Map<String, String> params,
			Object timeOut) throws ClientProtocolException, IOException,
			TimeoutException {
		return postUrl(url, params, "UTF-8", timeOut);
	}

	/**
	 * post提交数据
	 * 
	 * @param url
	 *            提交地址
	 * @param json
	 *            参数
	 * @param encoding
	 *            参数编码
	 * @param timeOut
	 *            超时时间：3*1000
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String postUrl(String url, String json, String encoding,
			Object timeOut) throws ClientProtocolException, IOException,
			TimeoutException {
		if (CommonMethodUtils.isNetWorkConnected(CampusInnApp.getInstance())) {
			List<NameValuePair> param = new ArrayList<NameValuePair>(); // 参数
			StringBuffer url_params = new StringBuffer();
			String result = null;
			HttpPost request = new HttpPost(url);
			request.addHeader("Content-Type", "application/json");
			request.addHeader("X-AUTH-TOKEN", "add token here");
			request.setEntity(new StringEntity(json, encoding));

			HttpClient client = new DefaultHttpClient();
			client.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut); // 设置请求超时时间
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
					timeOut); // 读取超时
			HttpResponse response = client.execute(request);
			// if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			// {
			// result = EntityUtils.toString(response.getEntity());
			// } else {
			// return null;
			// }
			result = EntityUtils.toString(response.getEntity());

			return result;
		} else {
			return null;
		}

	}

	/**
	 * post提交数据
	 * 
	 * @param url
	 *            提交地址
	 * @param params
	 *            参数
	 * @param encoding
	 *            参数编码
	 * @param timeOut
	 *            超时时间：3*1000
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String postUrl(String url, Map<String, String> params,
			String encoding, Object timeOut) throws ClientProtocolException,
			IOException, TimeoutException {
		if (CommonMethodUtils.isNetWorkConnected(CampusInnApp.getInstance())) {
			List<NameValuePair> param = new ArrayList<NameValuePair>(); // 参数
			StringBuffer url_prarams = new StringBuffer();
			String result = null;
			Iterator<Entry<String, String>> iterator = params.entrySet()
					.iterator();
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				param.add(new BasicNameValuePair(entry.getKey(), entry
						.getValue()));
				url_prarams.append("&").append(entry.getKey()).append("=")
						.append(entry.getValue());
			}
			HttpPost request = new HttpPost(url);
			request.addHeader("Content-Type", "application/json");
			/*
			 * JSONObject object = new JSONObject(); try {
			 * object.put("categoryId", "3"); object.put("page", "1");
			 * object.put("rows", "15"); } catch (JSONException e) {
			 * e.printStackTrace(); } request.setEntity(new
			 * StringEntity(object.toString()));
			 */
			HttpEntity entity = new UrlEncodedFormEntity(param, encoding);
			if (url_prarams.length() > 0) {
				LogUtil.i(url + "?" + url_prarams.deleteCharAt(0).toString());
			} else {
				LogUtil.i(url);
			}
			request.setEntity(entity);

			HttpClient client = new DefaultHttpClient();
			client.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut); // 设置请求超时时间
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
					timeOut); // 读取超时
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity());
			} else {
				return null;
			}

			return result;
		} else {
			return null;
		}

	}

	public static String uploadFile(File file, String RequestURL) {
		String result = null;
		String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
		String PREFIX = "--", LINE_END = "\r\n";
		String CONTENT_TYPE = "multipart/form-data"; // 内容类型
		int TIME_OUT = 10 * 1000; // 超时时间
		String CHARSET = "utf-8"; // 设置编码
		try {
			URL url = new URL(RequestURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(TIME_OUT);
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoInput(true); // 允许输入流
			conn.setDoOutput(true); // 允许输出流
			conn.setUseCaches(false); // 不允许使用缓存
			conn.setRequestMethod("POST"); // 请求方式
			conn.setRequestProperty("Charset", CHARSET); // 设置编码
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
					+ BOUNDARY);

			if (file != null) {
				/**
				 * 当文件不为空，把文件包装并且上传
				 */
				DataOutputStream dos = new DataOutputStream(
						conn.getOutputStream());
				StringBuffer sb = new StringBuffer();
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINE_END);
				/**
				 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
				 * filename是文件的名字，包含后缀名的 比如:abc.png
				 */

				sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""
						+ file.getName() + "\"" + LINE_END);
				sb.append("Content-Type: application/octet-stream; charset="
						+ CHARSET + LINE_END);
				sb.append(LINE_END);
				dos.write(sb.toString().getBytes());
				InputStream is = new FileInputStream(file);
				byte[] bytes = new byte[1024];
				int len = 0;
				while ((len = is.read(bytes)) != -1) {
					dos.write(bytes, 0, len);
				}
				is.close();
				dos.write(LINE_END.getBytes());
				byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
						.getBytes();
				dos.write(end_data);
				dos.flush();
				/**
				 * 获取响应码 200=成功 当响应成功，获取响应的流
				 */
				// int res = conn.getResponseCode();
				// Log.e(TAG, "response code:"+res);
				// if(res==200)
				// {
				// Log.e(TAG, "request success");
				InputStream input = conn.getInputStream();
				StringBuffer sb1 = new StringBuffer();
				int ss;
				while ((ss = input.read()) != -1) {
					sb1.append((char) ss);
				}
				result = sb1.toString();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 通过拼接的方式构造请求内容，实现参数传输以及文件传输
	 * 
	 * @param actionUrl
	 *            访问的服务器URL
	 * @param params
	 *            普通参数
	 * @param files
	 *            文件参数
	 * @return
	 * @throws IOException
	 */
	public static String postFiles(String actionUrl,
			Map<String, String> params, Map<String, File> files, String filename)
			throws IOException {

		String BOUNDARY = "--------------et567z";
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";
		StringBuilder sb2 = null;// 存放上传之后的返回结果

		URL uri = new URL(actionUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(60000); // 缓存的最长时间
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false); // 不允许使用缓存
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);

		// 首先组拼文本类型的参数
		StringBuilder sb = new StringBuilder();
		for (Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + LINEND);
			sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
			sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
		}

		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());
		outStream.write(sb.toString().getBytes());
		InputStream in = null;

		// 发送文件数据
		int res = 0;
		if (files != null) {
			for (Entry<String, File> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				// name是post中传参的键 filename是文件的名称
				sb1.append("Content-Disposition: form-data; name=\"Filedata\"; filename=\""
						+ filename + "\"" + LINEND);
				sb1.append("Content-Type: application/octet-stream; charset="
						+ CHARSET + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());

				InputStream is = new FileInputStream(file.getValue());
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = is.read(buffer)) != -1) {
					outStream.write(buffer, 0, len);
				}

				is.close();
				outStream.write(LINEND.getBytes());
			}

			// 请求结束标志
			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
			outStream.write(end_data);
			outStream.flush();
			// 得到响应码
			res = conn.getResponseCode();
			if (res == 200) {

				try {
					in = conn.getInputStream();
				} catch (Exception e) {
				}

				int ch;
				sb2 = new StringBuilder();
				while ((ch = in.read()) != -1) {
					sb2.append((char) ch);
				}
				return sb2.toString();
			}
			outStream.close();
			conn.disconnect();
		}
		return res + "";
	}

	// 以数据流的形式传参
	public static String postFileFromBytes(String actionUrl,
			Map<String, String> params, Map<String, byte[]> files)
			throws Exception {
		StringBuilder sb2 = null;
		String BOUNDARY = UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";

		URL uri = new URL(actionUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(6 * 1000); // 缓存的最长时间
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false); // 不允许使用缓存
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);

		// 首先组拼文本类型的参数
		StringBuilder sb = new StringBuilder();
		for (Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + LINEND);
			sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
			sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
		}

		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());
		outStream.write(sb.toString().getBytes());
		InputStream in = null;
		// 发送文件数据
		if (files != null) {
			for (Entry<String, byte[]> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\"pic\"; filename=\""
						+ file.getKey() + "\"" + LINEND);
				sb1.append("Content-Type: application/octet-stream; charset="
						+ CHARSET + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());

				outStream.write(file.getValue());

				outStream.write(LINEND.getBytes());
			}

			// 请求结束标志
			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
			outStream.write(end_data);
			outStream.flush();
			// 得到响应码
			int res = conn.getResponseCode();
			if (res == 200) {
				in = conn.getInputStream();
				int ch;
				sb2 = new StringBuilder();
				while ((ch = in.read()) != -1) {
					sb2.append((char) ch);
				}
				// System.out.println(sb2.toString());
			}
			outStream.close();
			conn.disconnect();
			// 服务器返回来的数据
			return sb2.toString();
		} else {
			return "Update icon Fail";
		}
		// return in.toString();
	}

}
